<?php

namespace app\middleware;

class CrossDomain
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        // 添加跨域的Headers
        $response->header([
            'Access-Control-Allow-Origin' => '*', // 允许任何源
            'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Accept, Authorization, X-Requested-With, Origin, X-CSRF-Token',
        ]);

        // 如果为OPTIONS请求，直接返回
        if (strtoupper($request->method()) == 'OPTIONS') {
            return $response;
        }

        // 继续处理其他请求
        return $response;
    }
}
